package edu.xmu.software.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import edu.xmu.software.dao.UserInfoDAO;
import edu.xmu.software.dao.UserAuthDAO;
import edu.xmu.software.pojo.UserInfo;

public class RegisterController extends AbstractController {

	private UserInfoDAO userInfoDAO;
	private UserAuthDAO userAuthDAO;
	
	public void setUserInfoDAO(UserInfoDAO userInfoDAO) {
		this.userInfoDAO = userInfoDAO;
	}
	public void setUserAuthDAO(UserAuthDAO userAuthDAO) {
		this.userAuthDAO = userAuthDAO;
	}
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserInfo userinfo = new UserInfo();
		//Map<String,String> retObject = new HashMap<String,String>();
		String userName = request.getParameter("Username");
		String password = request.getParameter("Password");
		String email = request.getParameter("email");
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		if (userInfoDAO.getUserInfoByUserName(userName) != null){
			response.sendRedirect("userRedirect.do?action=register&error=1");
			return null;
		}
		userinfo.setUsername(userName);
		userinfo.setPassword(password);
		userinfo.setEmail(email);
		userinfo.setName(name);
		userinfo.setPhone(phone);
		userinfo.setAddress(address);
		boolean retValue = userInfoDAO.addUserInfo(userinfo);
		System.out.println("here we go!" + retValue);
		if (retValue == true) {
			userAuthDAO.addUserAuth(userName);
		}
		System.out.println("ret: " + retValue);
		if (retValue == true){
			response.sendRedirect("userRedirect.do?action=login");
			return null;
		}else{
			response.sendRedirect("userRedirect.do?action=register&error=3");
			return null;
		}
	}

}
